package com.yoki.cloud.common.protocol.portal.msg;

import com.yoki.cloud.common.protocol.portal.msg.attr.MsgAttr;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2017/10/25$ 14:52$
 */
@NoArgsConstructor
public class PortalV1Msg extends AbstractPortalMsg {

    /**
     * 返回TLV数据报文
     *
     * @return
     */
    @Override
    public byte[] toByteArray() {
        byte[] headerBytes = getHander16Bytes();
        byte[] attrBytes = getAttrBytes();
        byte[] b = new byte[headerBytes.length + attrBytes.length];
        if (null != headerBytes && headerBytes.length > 0) {
            System.arraycopy(headerBytes, 0, b, 0, headerBytes.length);
        }
        b[AbstractPortalMsg.HEADER_LENGTH - 1] = (byte) this.attrList.size();
        if (null != attrBytes && attrBytes.length > 0) {
            System.arraycopy(attrBytes, 0, b, AbstractPortalMsg.HEADER_LENGTH, attrBytes.length);
        }
        return b;
    }

    @Override
    public void parse(byte[] input) {

        if (null != input && input.length >= AbstractPortalMsg.HEADER_LENGTH) {
            byte[] headerBytes = new byte[AbstractPortalMsg.HEADER_LENGTH];
            System.arraycopy(input, 0, headerBytes, 0, headerBytes.length);
            this.parseHeader(headerBytes);

            int attrNum = input[AbstractPortalMsg.HEADER_LENGTH - 1];
            byte[] attrBytes = new byte[input.length - AbstractPortalMsg.HEADER_LENGTH];
            System.arraycopy(input, AbstractPortalMsg.HEADER_LENGTH, attrBytes, 0, attrBytes.length);
            parseAttr(attrBytes, attrNum);
        }

    }



    public PortalV1Msg(int ver, int type, int serialNo, int reqId, String userIp, int errCode, int attrNum, List<MsgAttr> attr) {
        super();
        this.ver = ver;
        this.type = type;
        this.serialNo = serialNo;
        this.reqId = reqId;
        this.userIp = userIp;
        this.errCode = errCode;
        this.attrNum = attrNum;
        this.attrList = attr;
    }

    public PortalV1Msg(int ver, int type, int papChap, int rsvd, int serialNo, int reqId, String userIp, int userPort,
                       int errCode, int attrNum, List<MsgAttr> attr) {
        super();
        this.ver = ver;
        this.type = type;
        this.papChap = papChap;
        this.rsvd = rsvd;
        this.serialNo = serialNo;
        this.reqId = reqId;
        this.userIp = userIp;
        this.userPort = userPort;
        this.errCode = errCode;
        this.attrNum = attrNum;
        this.attrList = attr;
    }

}
